package com.runccyy.service.impl;

import cn.hutool.Hutool;
import cn.hutool.http.HttpUtil;
import com.runccyy.dao.mapper.UserMapper;
import com.runccyy.dao.model.UserPO;
import com.runccyy.service.UserService;
import com.runccyy.service.model.AuthInfo;
import com.runccyy.service.model.WxSession;
import com.runccyy.utils.GsonUtil;
import com.runccyy.utils.MD5Util;
import com.runccyy.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public UserPO getUserById(Long userId) {
        return userMapper.getById(userId);
    }
    @Override
    public Long insertUser(UserPO user) {
        if (Objects.isNull(user.getId())){
            userMapper.insertUser(user);
            return user.getId();
        }
        userMapper.updateUserInfo(user);
        return user.getId();
    }

    @Override
    public UserPO getUserByNameAndDepartment(String name, String department) {
        return userMapper.selectUserByNameAndDepartment(name, department);
    }

    @Override
    public AuthInfo authorize(String jsCode) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid",appId);
        paramMap.put("secret",secret);
        paramMap.put("js_code",jsCode);
        paramMap.put("grant_type","authorization_code");
        String s = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        WxSession wxSession = GsonUtil.fromJson(s, WxSession.class);
        if (!validErrorCode(wxSession)){
            return null;
        }
        String authInfo = String.format("wx.authorize:%s@k%s", wxSession.getOpenid(), wxSession.getSession_key());
        String auth = MD5Util.encrypt(authInfo);
        redisUtil.set(auth,authInfo);
        UserPO byOpenId = userMapper.getByOpenId(wxSession.getOpenid());
        AuthInfo authInfoBO = new AuthInfo();
        authInfoBO.setAuth(auth);
        authInfoBO.setHasProfile(byOpenId != null);
        authInfoBO.setOpenId(wxSession.getOpenid());
        return authInfoBO;
    }

    @Override
    public UserPO getUserByOpenId(String openId) {
        return userMapper.getByOpenId(openId);
    }

    private Boolean validErrorCode(WxSession wxSession) {
        if (wxSession.getErrcode() == 0){
            return true;
        }
        log.error("error code:{},error msg:{}",wxSession.getErrcode(),wxSession.getErrmsg());
        return false;
    }
}
